package com.heima.comment.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.heima.comment.service.CommentHotService;
import com.heima.comment.service.CommentService;
import com.heima.common.exception.CustException;
import com.heima.feigns.UserFeign;
import com.heima.model.comment.dtos.CommentDTO;
import com.heima.model.comment.dtos.CommentLikeDTO;
import com.heima.model.comment.dtos.CommentSaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.vos.ApCommentVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    UserFeign userFeign;
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    CommentHotService commentHotService;
    /**
     * 保存评论
     * @return
     */
    @Override
    public ResponseResult saveComment(CommentSaveDTO dto) {
        // 1. 校验参数
        //   校验是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 2. 阿里云校验评论内容是否违规
        //    (简单:  此步不做      普通: 阿里云检测有问题提示      高级:  有问题不报异常，替换为**)
        // 3. 远程查询当前登陆用户信息
        ResponseResult<ApUser> apUserResult = userFeign.findUserById(user.getId());
        if (apUserResult.getCode() != 0 || apUserResult.getData() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE, "用户信息不存在");
        }
        // 4. 创建评论信息，并保存到mongo
        user = apUserResult.getData();
        ApComment apComment = new ApComment();
        apComment.setAuthorId(user.getId());
        apComment.setAuthorName(user.getName());
        apComment.setArticleId(dto.getArticleId());
        apComment.setType((short) 0);
        apComment.setContent(dto.getContent());
        apComment.setImage(user.getImage());
        apComment.setLikes(0);
        apComment.setReply(0);
        apComment.setFlag((short) 0);
        apComment.setCreatedTime(new Date());
        apComment.setUpdatedTime(new Date());
        mongoTemplate.save(apComment);
        return ResponseResult.okResult();
    }

    @Autowired
    RedissonClient redissonClient;
    /**
     * 点赞评论
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(CommentLikeDTO dto) {
        // 1. 参数校验
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        RLock lock = redissonClient.getLock("Likes-lock");
        lock.lock();
        ApComment apComment;
        try {
            // 2. 根据评论id查询评论数据， 为null返回错误信息
            apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
            if (apComment == null) {
                CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE, "评论信息不存在");
            }
            ApCommentLike commentLike = mongoTemplate.findOne(Query.query(Criteria.where("authorId").is(user.getId())
                    .and("commentId").is(dto.getCommentId())), ApCommentLike.class);
            // 3. 如果是点赞操作 判断是否已经点赞
            if (dto.getOperation() == 0) {
                // 点过赞提示 请勿重复点赞
                if (commentLike != null) {
                    CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE, "请勿重复点赞");
                }
                // 未点过赞   保存点赞信息到mongo
                ApCommentLike apCommentLike = new ApCommentLike();
                apCommentLike.setAuthorId(user.getId());
                apCommentLike.setCommentId(dto.getCommentId());
                apCommentLike.setOperation(dto.getOperation());
                mongoTemplate.save(apCommentLike);
                // 并修改评论信息的点赞数量( + 1)
                apComment.setLikes(apComment.getLikes() + 1);
                mongoTemplate.save(apComment);
                //计算热点评论评论
                if (apComment.getLikes() >= 10 && apComment.getFlag().shortValue() == 0) {
                    commentHotService.hotCommentExecutor(apComment);
                }
            }else {
                // 取消点赞操作
                if (commentLike == null) {
                    CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE, "该评论未被点赞");
                }
                // 删除点赞信息
                mongoTemplate.remove(commentLike);
                // 并修改评论信息的点赞数量( - 1) , 要判断下别减成负数
                apComment.setLikes(apComment.getLikes() <= 0 ? 0 : apComment.getLikes() - 1);
                mongoTemplate.save(apComment);
            }
        } finally {
            lock.unlock();
        }
        // 5. 返回结果时，需要返回点赞点赞数量  返回的key要求必须是:  likes
        Map<String, Integer> resultMap = new HashMap<>();
        resultMap.put("likes", apComment.getLikes());
        return ResponseResult.okResult(resultMap);
    }

    /**
     * 根据文章id查询评论列表
     * @return
     */
    @Override
    public ResponseResult findByArticleId(CommentDTO dto) {
        // 1. 参数校验
        //    校验size
        Integer size = dto.getSize();
        if (size == null || size <= 0) {
            size = 10;
        }
        Query query = Query.query(Criteria.where("articleId").is(dto.getArticleId())
                .and("flag").is(0).and("createdTime").lt(dto.getMinDate())).limit(size)
                .with(Sort.by(Sort.Direction.DESC, "createdTime"));
        // 2. 根据条件查询评论列表 并按照时间倒序排序
        // 文章评论的首页
        List<ApComment> apCommentList;
        if (dto.getIndex().intValue() == 1) {
            //查询热点评论  5
            Query hotQuery = Query.query(Criteria.where("articleId").is(dto.getArticleId())
                    .and("flag").is(1)).with(Sort.by(Sort.Direction.DESC, "likes"));
            apCommentList = mongoTemplate.find(hotQuery, ApComment.class);
            // 热点集合不为空
            if (CollectionUtils.isNotEmpty(apCommentList)) {
                size = size - apCommentList.size();
                List<ApComment> normalComments = mongoTemplate.find(query, ApComment.class);
                apCommentList.addAll(normalComments);
            } else {
                apCommentList = mongoTemplate.find(query, ApComment.class);
            }
        } else {
            apCommentList = mongoTemplate.find(query, ApComment.class);
        }
//        List<ApComment> apCommentList = mongoTemplate.find(query, ApComment.class);
        // 3. 判断当前用户是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            // 4. 如果未登录直接返回评论列表
            return ResponseResult.okResult(apCommentList);
        }
        // 5. 如果登录了 需要检查在当前评论列表中 哪些评论登陆人点赞过
        // 获取文章对应的所有评论ID列表
        List<String> idList = apCommentList.stream()
                .map(ApComment::getId)
                .collect(Collectors.toList());
        // 查询 点赞批量列表 按照评论id 筛选
        List<ApCommentLike> apCommentLikes = mongoTemplate.find(
                Query.query(Criteria.where("commentId").in(idList)
                        .and("authorId").is(user.getId()))
                , ApCommentLike.class);
        // 遍历当前用户点赞列表 和当前评论列表
        if (CollectionUtils.isNotEmpty(apCommentList)
                && CollectionUtils.isNotEmpty(apCommentLikes)) {
            // 获取点过赞的评论id
            List<String> commentIds = apCommentLikes.stream()
                    .map(ApCommentLike::getCommentId).collect(Collectors.toList());
            // 遍历评论列表，将comment 转为 commentVO
            return ResponseResult.okResult(apCommentList.stream()
                    .map(comment -> parseCommentVO(comment, commentIds)));
        }
        return ResponseResult.okResult(apCommentList);
    }

    private ApCommentVo parseCommentVO(ApComment apComment, List<String> commentIds) {
        ApCommentVo apCommentVo = new ApCommentVo();
        BeanUtils.copyProperties(apComment, apCommentVo);
        //遍历当前用户点赞列表
        if (commentIds.contains(apCommentVo.getId())) {
            apCommentVo.setOperation((short) 0);
        }
        return apCommentVo;
    }
}